package com.wjq.randomplay;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.wjq.randomplay.activity.CityListActivity;
import com.wjq.randomplay.base.BaseActivity;
import com.wjq.randomplay.util.PreferencesUtils;
import com.wjq.randomplay.util.T;

import java.util.ArrayList;
import java.util.Random;

import butterknife.Bind;
import butterknife.OnClick;

public class MainActivity extends BaseActivity {
    @Bind(R.id.tv_result)
    TextView mTvResult;

    @Override
    public void initView() {
        super.initView();
        mTvRight.setText("城市列表");
        mArrayList = new ArrayList<>();
        mIvLeft.setVisibility(View.INVISIBLE);
        mIvLeft.setClickable(false);
        mTvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showActivity(new Intent(mContext, CityListActivity.class));
            }
        });
    }

    @OnClick(R.id.tv_random)
    public void mRandomClick() {
        getList();
        if (mArrayList.size() == 0) {
            T.showShort(mContext, "您还未添加城市哦！");
            return;
        }
        if (mArrayList.size() == 1) {
            T.showShort(mContext, "您只添加了一个城市！");
            mTvResult.setText(mArrayList.get(0));
        }
        if (mArrayList.size() > 1) {
            startRandom();
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onNetErrorClick() {

    }

    ArrayList<String> mArrayList;

    private void getList() {
        mArrayList.clear();
        String str = PreferencesUtils.getPreferences(mContext, PreferencesUtils.CITY_LIST);
        if (TextUtils.isEmpty(str)) {
            return;
        }
        String[] sArray = str.split(",");
        for (int i = 0; i < sArray.length; i++) {
            mArrayList.add(sArray[i]);
        }
    }

    private void startRandom() {
        int randomNum = new Random().nextInt(mArrayList.size());
        mTvResult.setText(mArrayList.get(randomNum));
    }
}
